package com.swak.utils;

import java.util.Arrays;

/**
 * see com.swak.utils.ObjectUtils
 *
 * @author lifeng
 */
public class Objects {

	// Null-safe equals/hashCode
	// -----------------------------------------------------------------------

	/**
	 * <p>
	 * Compares two objects for equality, where either one or both objects may be
	 * {@code null}.
	 * </p>
	 *
	 * <pre>
	 * Objects.equals(null, null)                  = true
	 * Objects.equals(null, "")                    = false
	 * Objects.equals("", null)                    = false
	 * Objects.equals("", "")                      = true
	 * Objects.equals(Boolean.TRUE, null)          = false
	 * Objects.equals(Boolean.TRUE, "true")        = false
	 * Objects.equals(Boolean.TRUE, Boolean.TRUE)  = true
	 * Objects.equals(Boolean.TRUE, Boolean.FALSE) = false
	 * </pre>
	 *
	 * @param object1 the first object, may be {@code null}
	 * @param object2 the second object, may be {@code null}
	 * @return {@code true} if the values of both objects are the same
	 */
	public static boolean equals(Object object1, Object object2) {
		if (object1 == object2) {
			return true;
		}
		if (object1 == null || object2 == null) {
			return false;
		}
		return object1.equals(object2);
	}

	/**
	 * <p>
	 * Gets the hash code of an object returning zero when the object is
	 * {@code null}.
	 * </p>
	 *
	 * <pre>
	 * Objects.hashCode(null)   = 0
	 * Objects.hashCode(obj)    = obj.hashCode()
	 * </pre>
	 *
	 * @param obj the object to obtain the hash code of, may be {@code null}
	 * @return the hash code of the object, or zero if null
	 * @since 2.1
	 */
	public static int hashCode(Object obj) {
		// hashCode(Object) retained for performance, as hash code is often critical
		return obj == null ? 0 : obj.hashCode();
	}

	/**
	 * Generates a hash code for multiple values. The hash code is generated by
	 * calling {@link Arrays#hashCode(Object[])}. Note that array arguments to this
	 * method, with the exception of a single Object array, do not get any special
	 * handling; their hash codes are based on identity and not contents.
	 *
	 * <p>
	 * This is useful for implementing {@link Object#hashCode()}. For example, in an
	 * object that has three properties, {@code x}, {@code y}, and {@code z}, one
	 * could write:
	 * 
	 * <pre>
	 *    {@code
	 *   public int hashCode() {
	 *     return Objects.hashCode(getX(), getY(), getZ());
	 *   }}
	 * </pre>
	 *
	 * <p>
	 * <b>Warning:</b> When a single object is supplied, the returned hash code does
	 * not equal the hash code of that object.
	 *
	 * <p>
	 * <b>Note for Java 7 and later:</b> This method should be treated as
	 * deprecated; use {@link java.util.Objects#hash} instead.
	 */
	public static int hashCode(Object... objects) {
		return Arrays.hashCode(objects);
	}
}
